﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

using Microsoft.Office.Interop.Word;

/// <summary>
///  模組: 檔案上傳 Module
///  作者: Adams <adams@netdb.com.tw>
///  修改: 2013-3-1
///  目的: 用來處理檔案上傳以及下載的共用元件
///  參數: 
/// </summary>
public class FileUtil
{
    public static void UploadMultiFiles(string savepath, Panel FileUploadHost)
    {
        if (!System.IO.Directory.Exists(savepath))
        {
            System.IO.Directory.CreateDirectory(savepath);
        }

        foreach (var control in FileUploadHost.Controls)
        {
            FileUpload file_upload = control as FileUpload;
            if (file_upload != null)
            {
                if (file_upload.HasFiles)
                {
                    try
                    {
                        foreach (HttpPostedFile postedFile in file_upload.PostedFiles)
                        {
                            String fileExtension = System.IO.Path.GetExtension(postedFile.FileName).ToLower();
                            String fileName = System.IO.Path.GetFileName(postedFile.FileName).ToLower();
                            String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
                            postedFile.SaveAs(savepath + "\\" + fileName);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
    }

    public static void GetFilesList(string savepath, GridView gv)
    {
        if (!System.IO.Directory.Exists(savepath))
        {
            //System.IO.Directory.CreateDirectory(savepath);
            return;
        }
        System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(savepath);
        gv.DataSource = d.GetFiles();
        gv.DataBind();
    }

    public static void DisplayAttachmentFiles(PlaceHolder placeHolder, string FolderName)
    {
        string savepath =
            HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["UploadFilePath"].ToString()
            + FolderName);
        if (System.IO.Directory.Exists(savepath))
        {
            var files = from f in new System.IO.DirectoryInfo(savepath).GetFiles()
                        select f;
            if (files.Count() > 0)
            {
                //placeHolder.Controls.Add(new LiteralControl("<br/> Attachments Files：<br/>"));
                foreach (var file in files)
                {
                    placeHolder.Controls.Add(new LiteralControl("<br/>"));
                    Image img = new Image();
                    img.Width = 16;
                    img.ImageUrl = "~/images/download.gif";
                    placeHolder.Controls.Add(img);
                    HyperLink link = new HyperLink();
                    link.Text = file.Name;
                    link.NavigateUrl = string.Format("~/Announcement/DownloadHandler.ashx?Fn={0}&Bid={1}"
                        , System.Web.HttpUtility.UrlEncode(file.Name)
                        , System.Web.HttpUtility.UrlEncode(FolderName));
                    placeHolder.Controls.Add(link);
                }
            }

        }

    }

    public static void DownloadFile(string FileApplicationPath)
    {
        try
        {
            string filename = Path.GetFileName(HttpContext.Current.Server.MapPath(FileApplicationPath));
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Expires = 0;
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename="
                + Convert.ToChar(34)
                + System.Web.HttpUtility.UrlPathEncode(filename)
                + Convert.ToChar(34));
            HttpContext.Current.Response.Charset = "utf-8";
            HttpContext.Current.Response.ContentType = "Application/octet-stream";
            HttpContext.Current.Response.WriteFile(FileApplicationPath);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
        catch (Exception ex)
        {
            throw ex;
        }       
    }

    public static void DownloadFile(string FileApplicationPath,string FileName)
    {
      try
      {
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Expires = 0;
        HttpContext.Current.Response.Buffer = true;
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename="
            + Convert.ToChar(34)
            + System.Web.HttpUtility.UrlPathEncode(FileName)
            + Convert.ToChar(34));
        HttpContext.Current.Response.Charset = "utf-8";
        HttpContext.Current.Response.ContentType = "Application/octet-stream";
        HttpContext.Current.Response.WriteFile(FileApplicationPath);
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
      }
      catch (Exception ex)
      {
        throw ex;
      }

    }   

    public static void ConvertWordToPDF(string WordFile, string PDFFile)
    {
        ApplicationClass xApp = new ApplicationClass();
        try
        {
            Document doc = xApp.Documents.Open(WordFile);
            if (doc!=null)
            {
              if (File.Exists(PDFFile)) File.Delete(PDFFile);
              doc.ExportAsFixedFormat(PDFFile,
                  WdExportFormat.wdExportFormatPDF,
                  false,
                  WdExportOptimizeFor.wdExportOptimizeForPrint,
                  WdExportRange.wdExportAllDocument);
              doc.Close();
              doc = null;    
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (xApp != null)
            {
                xApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xApp);
                xApp = null;
            }
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }

    public static void WriteHeaderAndFooterToWord(string sourcefile, string Header, string Footer)
    {
        ApplicationClass xApp = new ApplicationClass();
        try
        {
            Document docx = xApp.Documents.Open(sourcefile);
            if (docx!=null)
            {
              foreach (Section section in docx.Sections)
              {
                Range headerRange = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                headerRange.Fields.Add(headerRange, WdFieldType.wdFieldPage);
                headerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                headerRange.Text = Header;
              }

              foreach (Microsoft.Office.Interop.Word.Section wordSection in docx.Sections)
              {
                Range footerRange = wordSection.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                footerRange.Font.ColorIndex = WdColorIndex.wdDarkRed;
                footerRange.Font.Size = 8; //字型設定為8px
                footerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                wordSection.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text = Footer;
              }
              docx.Save();
              docx.Close();
              docx = null;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (xApp != null)
            {
                xApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xApp);
                xApp = null;
            }
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}